const SIDE_PANEL_PATH = 'popup.html';
const DEFAULT_MODEL = 'openrouter/llama-3.1-8b-instruct';

async function enableSidePanel() {
    try {
        await chrome.sidePanel.setOptions({ path: SIDE_PANEL_PATH, enabled: true });
    } catch (error) {
        console.error('设置 Side Panel 失败:', error);
    }
}

chrome.runtime.onInstalled.addListener(() => {
    enableSidePanel();
});

chrome.runtime.onStartup.addListener(() => {
    enableSidePanel();
});

chrome.action.onClicked.addListener(async (tab) => {
    try {
        await chrome.sidePanel.open({ tabId: tab.id });
    } catch (error) {
        console.error('打开 Side Panel 失败:', error);
    }
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message?.action === 'openSidePanel' && sender?.tab?.id) {
        chrome.sidePanel.open({ tabId: sender.tab.id }).catch((error) => {
            console.error('打开 Side Panel 失败:', error);
        });
        sendResponse({ success: true });
        return true;
    }
    return false;
});

chrome.runtime.onConnect.addListener((port) => {
    if (port.name !== 'openrouter-stream') {
        return;
    }

    let active = false;

    port.onMessage.addListener((message) => {
        if (message?.type === 'start' && !active) {
            active = true;
            streamOpenRouter(port, message.payload).catch((error) => {
                console.error('OpenRouter 流式请求失败:', error);
                if (port) {
                    port.postMessage({ type: 'error', error: error?.message || String(error) });
                }
            });
        }
    });

    port.onDisconnect.addListener(() => {
        active = false;
    });
});

async function streamOpenRouter(port, payload = {}) {
    const {
        baseUrl = 'https://openrouter.ai/api/v1',
        apiKey,
        model = DEFAULT_MODEL,
        messages,
        params = {},
        appUrl = 'https://pg-zdm.local',
        appTitle = 'PG-ZDM Shopping Assistant'
    } = payload;

    if (!apiKey) {
        port.postMessage({ type: 'error', error: '缺少 OpenRouter API Key' });
        return;
    }

    try {
        const response = await fetch(`${baseUrl}/chat/completions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`,
                'HTTP-Referer': appUrl,
                'X-Title': appTitle
            },
            body: JSON.stringify({
                model,
                messages,
                stream: true,
                ...params
            })
        });

        if (!response.ok) {
            let detail = `${response.status}`;
            try {
                const errorBody = await response.json();
                detail = errorBody?.error?.message || JSON.stringify(errorBody);
            } catch (err) {
                detail = await response.text();
            }
            port.postMessage({ type: 'error', error: `OpenRouter 请求失败: ${detail}` });
            return;
        }

        if (!response.body) {
            const text = await response.text();
            if (text) {
                port.postMessage({ type: 'chunk', data: text });
            }
            port.postMessage({ type: 'end' });
            return;
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let buffer = '';

        try {
            while (true) {
                const { value, done } = await reader.read();
                if (done) {
                    break;
                }
                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                buffer = lines.pop() || '';
                processSseLines(lines, port);
            }

            if (buffer) {
                processSseLines([buffer], port);
            }

            port.postMessage({ type: 'end' });
        } finally {
            reader.releaseLock();
        }
    } catch (error) {
        port.postMessage({ type: 'error', error: error?.message || String(error) });
    }
}

function processSseLines(lines, port) {
    for (const rawLine of lines) {
        const line = rawLine.trim();
        if (!line || !line.startsWith('data:')) {
            continue;
        }

        const data = line.slice(5).trim();
        if (!data || data === '[DONE]') {
            continue;
        }

        try {
            const parsed = JSON.parse(data);
            const delta = parsed?.choices?.[0]?.delta;
            if (delta?.content) {
                port.postMessage({ type: 'chunk', data: delta.content });
            }
        } catch (error) {
            console.warn('解析 OpenRouter 流式数据失败:', error, line);
        }
    }
}
